package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"oct30-exam/cache"
	"oct30-exam/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var article []models.Article
	redis_key := "article_list_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Offset(offset).Limit(size).Find(&article).Order("id DESC")
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}
	var count int64
	models.DB.Count(&count)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"article": article,
			"count":   count,
		},
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	redis_key := "article_detail_" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Where("id = ?", id).First(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}

func Collection(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var collection models.Collection
	collection.ArticleID = id
	err := models.DB.Create(&collection).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}
	redis_key := "article_collection_" + strconv.Itoa(id)
	jsonData, _ := json.Marshal(collection)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
